package com.awakening.EmbeddedChannel;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.TooLongFrameException;

import java.util.List;

/**
 * @Author:AwakeningCode
 * @Date: Created in 14:43 2018\3\8 0008
 */
public class FrameChunkDecoder extends ByteToMessageDecoder{

    private final int maxFrameSize;

    public FrameChunkDecoder(int maxFrameSize) {
        this.maxFrameSize = maxFrameSize;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext,
                          ByteBuf in, List<Object> out) throws Exception {
        int readableBytes = in.readableBytes();
        //如果该帧太大，则丢弃它并抛出异常
        if (readableBytes > maxFrameSize){
            //discard the bytes
            in.clear();
            throw new TooLongFrameException();
        }
        //从ByteBuf中读取一个新的帧
        ByteBuf buf = in.readBytes(readableBytes);
        //将该帧添加到解码消息的List中
        out.add(buf);
    }
}
